package com.ruoyi.common.utils.security;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.core.env.Environment;

import java.math.BigInteger;

public abstract class SMUtil {

    public static final String SESSION_ATTR_SM2 = "SESSION_ATTR_SM2";

    /**
     * 加密(公钥)
     * @param sm2
     * @param str
     * @return
     */
    public static String sm2Enc(SM2 sm2, String str) {
        if (StrUtil.isEmpty(str)) {
            return "";
        }
        return sm2.encryptBcd(str, KeyType.PublicKey);
    }

    /**
     * 解密(私钥)
     * @param sm2
     * @param str
     * @return
     */
    public static String sm2Dec(SM2 sm2, String str) {
        if (StrUtil.isEmpty(str)) {
            return "";
        }
        return Base64.decodeStr(sm2.decryptStrFromBcd(str, KeyType.PrivateKey));
    }

    /**
     * 国密SM2公钥
     * @param sm2
     * @return
     */
    public static String sm2PublicKey(SM2 sm2) {
        return new BigInteger(sm2.getPublicKey().getEncoded()).toString(16);
    }

    /**
     * 国密SM2
     * @return
     */
    public static SM2 sm2() {
        return SmUtil.sm2().init();
    }

    /**
     * SM4加密
     * @param str
     * @return
     */
    public static String sm4Enc(String str) {
        if (StrUtil.isEmpty(str)) {
            return "";
        }
        return sm4().encryptBase64(str);
    }

    /**
     * SM4解密
     * @param str
     * @return
     */
    public static String sm4Dec(String str) {
        if (StrUtil.isEmpty(str)) {
            return "";
        }
        return sm4().decryptStr(str);
    }

    /**
     * 获取SM4
     * @return
     */
    public static SymmetricCrypto sm4() {
        Environment env = SpringUtils.getBean(Environment.class);
        String sm4Key = env.getProperty("sm4.key");
        return SmUtil.sm4(Base64.decode(sm4Key));
    }
}
